package com.ruoyi.teacher.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.weChatRobot.utils.WechatRobotUtil;
import com.ruoyi.employment.api.RemoteEmploymentService;
import com.ruoyi.employment.api.domain.TeacherToEmploymentDto;
import com.ruoyi.teacher.domain.Teacher;
import com.ruoyi.teacher.domain.TeacherReport;
import com.ruoyi.teacher.mapper.TeacherMapper;
import com.ruoyi.teacher.mapper.TeacherReportMapper;
import com.ruoyi.teacher.service.ITeacherReportService;
import com.ruoyi.teaching.api.RemoteTeachingService;
import com.ruoyi.teaching.api.domain.TeachingTraceDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 老师日报Service业务层处理
 *
 * @author clid
 * @date 2024-03-26
 */
@Service
public class TeacherReportServiceImpl implements ITeacherReportService {
    @Autowired
    private TeacherReportMapper teacherReportMapper;
    @Autowired
    private RemoteEmploymentService remoteEmploymentService;
    @Autowired
    private RemoteTeachingService remoteTeachingService;
    @Autowired
    private TeacherMapper teacherMapper;

    /**
     * 查询老师日报
     *
     * @param id 老师日报主键
     * @return 老师日报
     */
    @Override
    public TeacherReport selectTeacherReportById(Long id) {
        return teacherReportMapper.selectTeacherReportById(id);
    }

    /**
     * 查询老师日报列表
     *
     * @param teacherReport 老师日报
     * @return 老师日报
     */
    @Override
    public List<TeacherReport> selectTeacherReportList(TeacherReport teacherReport) {
        return teacherReportMapper.selectTeacherReportList(teacherReport);
    }

    /**
     * 新增老师日报
     *
     * @param teacherReport 老师日报
     * @return 结果
     */
    @Override
    public int insertTeacherReport(TeacherReport teacherReport) {
        Long loginId = SecurityContextHolder.getUserId();
        Teacher teacher = teacherMapper.findbyLoginId(String.valueOf(loginId));
        String teacherName = teacher.getName();
        teacherReport.setTeacherName(teacherName);
        teacherReport.setTeacherId(teacher.getId());
        teacherReport.setTeacherType(teacher.getTeacherType());
        teacherReport.setCampusId(Long.valueOf(teacher.getCampusId()));
        teacherReport.setSubjectId(Long.valueOf(teacher.getSubjectId()));
        //判断是否为空
        //获取就业跟踪
        List<TeacherToEmploymentDto> employmentTracking = teacherReport.getEmploymentTracking();
        if (CollUtil.isNotEmpty(employmentTracking)) {
            List<TeacherToEmploymentDto> teacherToEmploymentDtoList = employmentTracking.stream()
                    .filter(e -> e.getClassId() != null)
                    .peek(em -> {
                        em.setTrackMan(teacherName);
                    }).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(teacherToEmploymentDtoList)) {
                //远程调用就业服务
                R<Void> result = remoteEmploymentService.teacherToEmployment(teacherToEmploymentDtoList);
            }
        }
        //获取教学追踪
        List<TeachingTraceDto> teachingTracking = teacherReport.getTeachingTracking();
        if (CollUtil.isNotEmpty(teachingTracking)) {
            List<TeachingTraceDto> teachingTraceDtoList = teachingTracking.stream()
                    .filter(t -> t.getClassId() != null)
                    .peek(t -> {
                        t.setId(null);
                        t.setTeacherId(teacher.getId());
                        t.setTeacherName(teacherName);
                    }).collect(Collectors.toList());
            //远程调用教学服务
            if (CollUtil.isNotEmpty(teachingTraceDtoList)) {
                AjaxResult ajaxResult = remoteTeachingService.add(teachingTraceDtoList);
            }
        }
        teacherReport.setCreateTime(DateUtils.getNowDate());
        return teacherReportMapper.insertTeacherReport(teacherReport);
    }

    /**
     * 修改老师日报
     *
     * @param teacherReport 老师日报
     * @return 结果
     */
    @Override
    public int updateTeacherReport(TeacherReport teacherReport) {
        return teacherReportMapper.updateTeacherReport(teacherReport);
    }

    /**
     * 批量删除老师日报
     *
     * @param ids 需要删除的老师日报主键
     * @return 结果
     */
    @Override
    public int deleteTeacherReportByIds(Long[] ids) {
        return teacherReportMapper.deleteTeacherReportByIds(ids);
    }

    /**
     * 删除老师日报信息
     *
     * @param id 老师日报主键
     * @return 结果
     */
    @Override
    public int deleteTeacherReportById(Long id) {
        return teacherReportMapper.deleteTeacherReportById(id);
    }

    /**
     *
     * 定时统计异常
     */
    @Override
    public void abnormalTimingStatistics() {
        DateTime yesterday = DateUtil.offsetDay(DateUtil.date(), -1);
        List<Teacher> teacherList  = getAbnormalTeacher(yesterday);
        if (teacherList == null) return;
        //保存异常记录
        teacherList.stream().peek(t -> {
            t.setCreateTime(yesterday);
            t.setRemark("日报没有写");
        }).collect(Collectors.toList());
        teacherReportMapper.insertBatchReportAbnormal(teacherList);
    }

    /**
     * 定时通知教师日报
     */
    @Override
    public void timeNoticeTeacherReport() {
        DateTime now = DateUtil.date();
        List<Teacher> abnormalTeachers = getAbnormalTeacher(now);
        if (abnormalTeachers == null) return;
        //企业微信通知老师
        List<String> phones = abnormalTeachers.stream().map(Teacher::getPhone)
                .filter(Objects::nonNull).collect(Collectors.toList());
        WechatRobotUtil.sendTextMessage("可爱的叮咚提醒你,"+ DateUtil.format(now,"yyyy-MM-dd")+"的日报还没写哦~~~",phones);
    }


    /**
     * 获取未写日志的老师
     *
     * @param yesterday 昨天
     * @return {@link List}<{@link Teacher}>
     */
    private List<Teacher> getAbnormalTeacher(DateTime yesterday) {
        //获取所有的老师
        List<Teacher> teachers = teacherMapper.selectTeacherList(new Teacher());
        //获取所有老师的ids
        Map<Long, Teacher> teacherMap = teachers.stream()
                .collect(Collectors.toMap(Teacher::getId, t -> t));
        TeacherReport teacherReport = new TeacherReport();
        teacherReport.setReportTime(yesterday);
        //获取到昨天的所有打卡数据
        List<TeacherReport> yesterdayTeacherReport = teacherReportMapper.selectTeacherReportYesterday(teacherReport);
        if (CollUtil.isEmpty(yesterdayTeacherReport)) {
            //都没有打卡，保存全部日志
            List<Teacher> teacherList = teachers.stream().peek(t -> {
                t.setCreateTime(yesterday);
                t.setRemark("日报没有写");
            }).collect(Collectors.toList());
            teacherReportMapper.insertBatchReportAbnormal(teacherList);
            return null;
        }
        //移除已经写了日志的老师
        yesterdayTeacherReport.stream()
                .map(TeacherReport::getTeacherId)
                .forEach(teacherMap::remove);
        if (CollUtil.isEmpty(teacherMap)) {
            //全部都已经打卡
            return null;
        }
        return new ArrayList<>(teacherMap.values());
    }

}
